package com.whately.core.base.utils;

import com.whately.core.base.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class FileUtils {

    /**
     * 文件字节数组，解决重复读取的问题
     */
    public static byte[] coryMultipartFile2bytes(MultipartFile file){
        InputStream ins = null;
        try{
            ins = file.getInputStream();
            return inputStream2bytes(ins);
        }catch (IOException e){
            log.error("coryFile2ByteArray file io error ",e);
            throw new ServiceException(400,"read file input stream error");
        }finally{
            IOUtils.closeQuietly(ins);
        }
    }


    public static byte[] inputStream2bytes(InputStream ins)  {
        byte[] byteData ;
        try{
            byteData = IOUtils.toByteArray(ins);
        }catch (IOException e){
            log.error("inputStream2byte io error ",e);
            throw new ServiceException(400,"read file input stream to bytes error");
        }finally{
            IOUtils.closeQuietly(ins);
        }
        return byteData;
    }



    public static InputStream bytes2InputStream(byte[] bytes) {
        return new ByteArrayInputStream(bytes);
    }

}
